package com.why.extender.rpcextend.extend;



import com.why.extender.rpcextend.annotation.RpcConsumer;
import com.why.rpc.core.client.channel.ProxyClient;
import com.why.simpleboot.core.common.utils.SimpleIocUtils;
import com.why.simpleboot.core.core.ApplicationContext;
import com.why.simpleboot.core.extend.ImportBeforeBeanRegistrar;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: why-simpleboot-framework
 * @description:完client代理类的生成然后加入给容器，必须要提前生成，否则无法完成依赖注入
 * @author: @why
 * @create: 2021-06-15 15:01
 **/
public class RpcClientProxyRegistrar implements ImportBeforeBeanRegistrar {
    @Override
    public void registerBeans(ApplicationContext applicationContext, List<String> scanPackages, Class<?> mainClass) {
        String mainClassPosition = mainClass.getCanonicalName();
//        获得应该扫描的路径
        ConcurrentHashMap<Class<? extends Annotation>, Set<Class<?>>> classes = applicationContext.getClassFactory().getCLASSES();
        for (Map.Entry<Class<? extends Annotation>, Set<Class<?>>> entry : classes.entrySet()) {
            for (Class<?> aClass : entry.getValue()) {
                for (Field consumer : aClass.getDeclaredFields()) {
                    if (consumer.isAnnotationPresent(RpcConsumer.class)) {
                        String name = SimpleIocUtils.getBeanName(consumer.getType());
                        //完成代理类的生成
                        applicationContext.getBeanFactory().setBean(name, wrappedBean(consumer.getType()));
                    }
                }
            }
        }
    }
    /**
     * 完成代理类的生成
     *
     * @param bean
     * @return
     */
    private Object wrappedBean(Class<?> bean) {
        return ProxyClient.getProxy(bean);
    }


}

